package com.ooqiu.gaming.ui.person.history;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.api.entities.Article;
import com.ooqiu.gaming.base.BaseActivity;
import com.ooqiu.gaming.common.Constants;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.ui.article_detail.ArticleDetailActivity;
import com.ooqiu.gaming.ui.article_detail.VideoDetailActivity;
import com.ooqiu.gaming.ui.main.thread.index.content.IndexContentAdapter;
import com.ooqiu.gaming.view.Topbar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@Route(path = HistoryActivity.PATH, extras = Constants.ROUTER_EXTRA_NEED_LOGIN)
public class HistoryActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    public static final String PATH = "/user/history";


    List<Article> mArticles = new ArrayList<>();
    IndexContentAdapter mIndexContentAdapter;

    GamingApi mGamingApi;
    @BindView(R.id.topbar)
    Topbar mTopbar;
    @BindView(R.id.rv_history_list)
    RecyclerView mRvHistoryList;
    @BindView(R.id.swiper)
    FrameLayout mSwiper;
    private int page = 1;
    private boolean isRefresh;
    private boolean isSticky;
    @BindView(R.id.lay_sticky)
    View LAY_STICKY;



    @Override
    public int initContentView() {
        return R.layout.activity_history;
    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        mGamingApi = getApplicationComponent().getGamingApi();
    }

    @Override
    public void initUiAndListener() {

//        mSwiper.setOnRefreshListener(this);
        mRvHistoryList.setLayoutManager(new LinearLayoutManager(mContext));
        mRvHistoryList.setAdapter(mIndexContentAdapter = new IndexContentAdapter(mArticles));

//        mIndexContentAdapter.setEnableLoadMore(true);
//        mIndexContentAdapter.setOnLoadMoreListener(this, mRvHistoryList);

        mIndexContentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Article article = (Article) adapter.getItem(position);
                if (article.getContent_type() == 3) {
                    getRouter().build(VideoDetailActivity.PATH)
                            .withInt("news_id", article.getNews_id())
                            .navigation();
                } else {
                    getRouter().build(ArticleDetailActivity.PATH)
                            .withInt("news_id", article.getNews_id())
                            .navigation();
                }

            }
        });


//        mRvHistoryList.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                int pos;
//                if (dy > 0) {
//                     pos = mRvHistoryList.getChildAdapterPosition(recyclerView.findChildViewUnder(
//                            LAY_STICKY.getMeasuredWidth() / 2, LAY_STICKY.getMeasuredHeight() - 1));
//                } else {
//                     pos = mRvHistoryList.getChildAdapterPosition(recyclerView.findChildViewUnder(
//                            LAY_STICKY.getMeasuredWidth() / 2, LAY_STICKY.getMeasuredHeight() + 1));
//                }
//
//
//
//
//                if (pos < 0) {
//                    return;
//                }
//
//                // 找到RecyclerView的item中，和RecyclerView的getTop 向下相距5个像素的那个item
//                // (尝试2、3个像素位置都找不到，所以干脆用了5个像素)，
//                // 我们根据这个item，来更新吸顶布局的内容，
//                // 因为我们的StickyLayout展示的信息肯定是最上面的那个item的信息.
//
//                Article article = mIndexContentAdapter.getData().get(pos);
//
////                View stickyInfoView = recyclerView.findChildViewUnder(LAY_STICKY.getMeasuredWidth() / 2, 5);
//                if (article != null&& article.getItemType()==IndexContentAdapter.ITEM_HEADER) {
//                    ((TextView)LAY_STICKY.findViewById(R.id.tv_header)).setText(article.getTitle());
//                }
//
//                // 找到固定在屏幕上方那个FakeStickyLayout下面一个像素位置的RecyclerView的item，
//                // 我们根据这个item来更新假的StickyLayout要translate多少距离.
//                // 并且只处理HAS_STICKY_VIEW和NONE_STICKY_VIEW这两种tag，
//                // 因为第一个item的StickyLayout虽然展示，但是一定不会引起FakeStickyLayout的滚动.
//
//
//
//
//                View transInfoView = recyclerView.findChildViewUnder(
//                        LAY_STICKY.getMeasuredWidth() / 2, LAY_STICKY.getMeasuredHeight() + 1);
//
//
//                if (article != null && transInfoView != null) {
//                    int dealtY = transInfoView.getTop() - LAY_STICKY.getMeasuredHeight();
//
//                    // 如果当前item需要展示StickyLayout，
//                    // 那么根据这个item的getTop和FakeStickyLayout的高度相差的距离来滚动FakeStickyLayout.
//                    // 这里有一处需要注意，如果这个item的getTop已经小于0，也就是滚动出了屏幕，
//                    // 那么我们就要把假的StickyLayout恢复原位，来覆盖住这个item对应的吸顶信息.
//                    if (article.getItemType() == IndexContentAdapter.ITEM_HEADER) {
//                        if (transInfoView.getTop() > 0) {
//                            LAY_STICKY.setTranslationY(dealtY);
//                        } else {
//                            LAY_STICKY.setTranslationY(0);
//                        }
//                    } else {
//
//                            // 如果当前item不需要展示StickyLayout，那么就不会引起FakeStickyLayout的滚动.
//                            LAY_STICKY.setTranslationY(0);
//
//                    }
//                }
//            }
//        });




        onRefresh();

    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return mTopbar;
    }

    @Override
    protected View statusLayoutId() {
        return null;
    }


    @Override
    public void onRefresh() {
//        mSwiper.setRefreshing(true);
        page = 1;
        isRefresh = true;
        mArticles.clear();
        fetchHistory();
    }


    private void fetchHistory() {
        mGamingApi.fetchHistory(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<HistoryRecord>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(HistoryRecord record) {


                        if (!record.getList().getToday().isEmpty()) {
                            Article a = new Article();
                            a.setTitle("今天");
                            a.setContent_type(-1);

                            mArticles.add(a);
                            mArticles.addAll(record.getList().getToday());

                        }

                        if (!record.getList().getYesterday().isEmpty()) {
                            Article a = new Article();
                            a.setTitle("昨天");
                            a.setContent_type(-1);
                            mArticles.add(a);
                            mArticles.addAll(record.getList().getYesterday());

                        }


                        if (!record.getList().getByesterday().isEmpty()) {
                            Article a = new Article();
                            a.setTitle("前天");
                            a.setContent_type(-1);
                            mArticles.add(a);
                            mArticles.addAll(record.getList().getByesterday());

                        }

                        if (!record.getList().getEarly().isEmpty()) {
                            Article a = new Article();
                            a.setContent_type(-1);
                            a.setTitle("更早");
                            mArticles.add(a);
                            mArticles.addAll(record.getList().getEarly());

                        }


//
//                        LogUtil.json(mArticles);

                        mIndexContentAdapter.notifyDataSetChanged();

//                        if (isRefresh) {
//                            mArticles.clear();
//                            isRefresh = false;
//                        }
//                        mArticles.addAll(articles);

//
//                        if (articles.isEmpty()) {
//                            mIndexContentAdapter.loadMoreEnd(true);
//                        } else {
//                            mIndexContentAdapter.loadMoreComplete();
//                        }
//                        page++;
//                        mIndexContentAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
//                        mSwiper.setRefreshing(false);
                    }
                });
    }
}
